package larrys.pomodoro.domain.service;

import larrys.pomodoro.domain.entity.PomodoroUser;
import larrys.pomodoro.domain.entity.Role;
import larrys.pomodoro.domain.repository.BaseInfoRepository;
import larrys.pomodoro.domain.repository.UserRepository;
import larrys.pomodoro.form.SignupForm;
import larrys.pomodoro.util.AssertUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PomodoroUserService {

	private static Log logger = LogFactory.getLog(PomodoroUserService.class);

	@Autowired
	private UserRepository userRepository;

	private BaseInfoRepository baseInfoRepository;

	private Role userRole;

	@Required
	@Autowired
	public void setBaseInfoRepository(BaseInfoRepository baseInfoRepository) {
		this.baseInfoRepository = baseInfoRepository;
		userRole = baseInfoRepository.getRoleByName("ROLE_USER");
	}

	public boolean isUserEmailExist(String email) {
		AssertUtil.argumentNotNull(email, "email");
		logger.debug("Tring to find out if user[email:" + email
				+ "] already exists");

		PomodoroUser user = userRepository.getUserByEmail(email);
		boolean result = user != null;

		logger.debug("Returning " + result);
		return result;
	}

	public PomodoroUser getUserByEmail(String userEmail) {
		AssertUtil.argumentNotNull(userEmail, "userEmail");
		logger.debug("Tring to get user[email:" + userEmail + "]");

		PomodoroUser user = userRepository.getUserByEmail(userEmail);

		if (user != null) {
			logger.debug("Returning " + user);
		} else {
			logger.warn("PomodoroUser[email:" + userEmail + "] doesn't exist");
		}
		return user;
	}

	@Transactional
	public void addUser(SignupForm signupForm) {
		AssertUtil.argumentNotNull(signupForm, "signupForm");
		logger.debug("Tring to add " + signupForm);

		PomodoroUser newUser = new PomodoroUser(0, signupForm.getEmail());
		newUser.setUsername(signupForm.getUsername());
		newUser.setPassword(signupForm.getPassword());
		newUser.addRole(userRole);
		userRepository.addUser(newUser);

		logger.info("New " + newUser + " added successfully!");
	}

	@Transactional
	public void updateUser(PomodoroUser user) {
		AssertUtil.argumentNotNull(user, "user");
		logger.debug("Tring to update " + user);

		userRepository.updateUser(user);

		logger.info(user + " updated successfully!");
	}

	@Transactional
	public void deleteUserById(long id) {
		AssertUtil.validId(id);
		logger.debug("Tring to delete user[id:" + id + "]");

		userRepository.markUserDeletedById(id);

		logger.info("PomodoroUser[id:" + id + "] marked deleted successfully!");
	}
}
